package cn.minimelon.solon.service.warehouse.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.minimelon.solon.domain.warehouse.CertCodeQueryVO;
import cn.minimelon.solon.domain.warehouse.DeptBuyDetailVO;
import cn.minimelon.solon.domain.warehouse.GoodsCertInfo;
import cn.minimelon.solon.mapper.excel.TempTableMapper;
import cn.minimelon.solon.mapper.warehouse.DeptBuyMapper;
import cn.minimelon.solon.mapper.warehouse.GoodsInfoMapper;
import cn.minimelon.solon.service.warehouse.DeptBuyDetailService;
import cn.minimelon.solon.service.warehouse.DeptBuyService;
import lombok.extern.slf4j.Slf4j;
import org.beetl.sql.solon.annotation.Db;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class DeptBuyServiceImpl implements DeptBuyService {
    @Db("writer")
    private DeptBuyMapper deptBuyMapper;

    @Db("writer")
    private GoodsInfoMapper goodsInfoMapper;

    @Db("writer")
    private TempTableMapper tempTableMapper;

    @Inject
    private DeptBuyDetailService deptBuyDetailService;

    @Override
    public List<String> selectFinishGenBillList(String logicId) {
        List<String> idList = deptBuyMapper.selectWaitGenList(logicId);

        List<DeptBuyDetailVO> detailList = deptBuyDetailService.selectListWithCalcQty(idList, logicId, 1);
        List<String> resList = new ArrayList<>();
        for (String billId : idList) {
            List<DeptBuyDetailVO> subList = detailList.stream()
                    .filter(it -> StrUtil.equals(billId, it.getPid()))
                    .collect(Collectors.toList());
            if (CollUtil.isNotEmpty(subList)) {
                // 获取未完成的列
                List<DeptBuyDetailVO> newList = subList.stream().filter(o -> o.getTaskQty()
                        .compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());

                // 计算单元数
                BigDecimal pkgQty = newList.stream()
                        .map(sub -> sub.getTaskQty().divide(sub.getPkgDefQty(), RoundingMode.HALF_UP))
                        .reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
                log.info("DDD>>> billId:{} task:{}", billId, pkgQty);
                if (pkgQty.compareTo(BigDecimal.ZERO) == 0) {
                    resList.add(billId);
                }
            } else {
                log.info("DDD>>> billId:{} error", billId);
                resList.add(billId);
            }
        }
        return resList;
    }

    @Override
    public Integer selectErrorCertCode(CertCodeQueryVO query) {
        query.setSpd2DbName("spd");
        List<String> provIdList = ListUtil.toList("pd5c6","p1de1d","p1cf63","p00fb","p2a65","p6fc9","p92f0","p18813","p1de4a","pef80","p5a97","p1ea5d","pf62c","p1ef91");
        for (String provId : provIdList) {
            List<String> logList = new ArrayList<>();
            CertCodeQueryVO query2 = new CertCodeQueryVO();
            query2.setProvId(provId);
            List<GoodsCertInfo> goodsInfoList = goodsInfoMapper.selectModifiedByProvId(query2);
            for (GoodsCertInfo cert : goodsInfoList) {
                query2.setProvGoodsId(cert.getProvGoodsId());
                List<GoodsCertInfo> certList = goodsInfoMapper.selectRegCertByProvGoodsId(query2);
                if (CollUtil.isEmpty(certList)) {
                    String template = "provId:{}, provGoodsId:{}, certCode:{}, empty";
                    logList.add(StrUtil.format(template, provId, cert.getProvGoodsId(), cert.getCertCode()));
                } else {
                    List<String> certCodeList = certList.stream().map(GoodsCertInfo::getCertCode).collect(Collectors.toList());
                    if (certCodeList.contains(cert.getCertCode())) {
                        continue;
                    }
                    String template = "provId:{}, provGoodsId:{}, certCode:{}, newCode:{}";
                    logList.add(StrUtil.format(template, provId, cert.getProvGoodsId(), cert.getCertCode(), certCodeList.get(0)));
                }
            }
            try {
                if (CollUtil.isNotEmpty(logList)) {
                    writeFile(logList, provId, "empty333");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    @Override
    public void selectErrorRegInfo(CertCodeQueryVO query) {
        query.setSpd2DbName("spd");
        List<GoodsCertInfo> certList = goodsInfoMapper.selectRegCertCond(query);
        List<String> logList = new ArrayList<>();
        logList.add(StrUtil.format("{}, {}, {}, {}", "McmsRegistrationId", "CertCode", "Count1", "Count2"));
        for (GoodsCertInfo cert : certList) {
            CertCodeQueryVO query2 = new CertCodeQueryVO();
            query2.setSpd2DbName("spd");
            query2.setMcmsRegistrationId(cert.getMcmsRegistrationId());
            query2.setProvRegistrationId(cert.getProvRegistrationId());
            Integer mcmsCount = goodsInfoMapper.selectMcmsGoodsCount(query2);
            if (mcmsCount != null && mcmsCount > 50) {
                Integer provCount = goodsInfoMapper.selectProvGoodsCount(query2);
                if (provCount != null && mcmsCount - provCount > 0) {
                    log.info("DDD>>> cert:{} {} c1:{} c2:{}", cert.getMcmsRegistrationId(), cert.getCertCode(), mcmsCount, provCount);
                    logList.add(StrUtil.format("{}, {}, {}, {}", cert.getMcmsRegistrationId(), cert.getCertCode(), mcmsCount, provCount));
                }
            }
        }
        try {
            writeFile(logList, "hhhh", "ERROR_0618");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void selectDistrInfo(CertCodeQueryVO query) {
        query.setSpd2DbName("spd");
        List<GoodsCertInfo> certList = goodsInfoMapper.selectDistr3CertList(query);
        List<String> logList = new ArrayList<>();
        for (GoodsCertInfo goods : certList) {
            if (StrUtil.isEmpty(goods.getHosGoodsId())) {
                throw new RuntimeException("数据错误");
            }
            query.setHosGoodsId(goods.getHosGoodsId());
            GoodsCertInfo trueCert = goodsInfoMapper.selectTrue3CertCode(query);
            if (trueCert != null && !goods.getCertCode().equals(trueCert.getCertCode())) {
                log.info("DDD>>> hosGoodsId:{}, old>:{}, ttt>:{}", goods.getHosGoodsId(), goods.getCertCode(), trueCert.getCertCode());
                logList.add(StrUtil.format("DDD>>> hosGoodsId:{} old>:{} ttt>:{}",
                        goods.getHosGoodsId(), goods.getCertCode(), trueCert.getCertCode()));
            } else {
                log.info("DDD>>> hosGoodsId:{}, old>:{} 未找到", goods.getHosGoodsId(), goods.getCertCode());
                logList.add(StrUtil.format("DDD>>> hosGoodsId:{} old>:{} 未找到",
                        goods.getHosGoodsId(), goods.getCertCode()));
            }
        }
        try {
            writeFile(logList, query.getHosId(), "dist3-all");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void execReadFile(String directoryPath) {
        traverseDirectory(new File(directoryPath));
    }

    private void traverseDirectory(File directory) {
        // 检查是否为目录
        if (directory.isDirectory()) {
            File[] files = directory.listFiles(); // 获取目录下的所有文件和子目录
            if (files != null) {
                List<String> logList = new ArrayList<>();
                for (File file : files) {
                    if (file.isDirectory()) {
                        System.out.println("Provided path is not a directory.");
                    } else {
                        // 读取文件内容
                        readFile(file, logList);
                    }
                }
                try {
                    writeFile(logList, "cert_temp", "insert_all");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            System.out.println("Provided path is not a directory.");
        }
    }

    private void readFile(File file, List<String> logList) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] arr = line.split(",");
                System.out.println(arr[0]);
                String provId = readValue(arr[0]);
                String provGoodsId = readValue(arr[1]);
                String oldCode = readValue(arr[2]);
                String newCode = readValue(arr[3]);
                String template = "INSERT INTO `cert_temp` (`id`, `prov_id`, `prov_goods_id`, `old_code`, `new_code`) VALUES (uuid(), '{}', '{}', '{}', '{}');";
                logList.add(StrUtil.format(template, provId, provGoodsId, oldCode, newCode));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String readValue(String str) {
        int lastColonIndex = str.lastIndexOf(':'); // 查找最后一个冒号的位置
        if (lastColonIndex > -1) {
            // 获取最后一个冒号后的内容，并去除可能的前后空格
            return str.substring(lastColonIndex + 1).trim();
        } else {
            return str.trim();
        }
    }

    private void writeFile(List<String> logList, String hosId, String type) throws Exception {
        String fileName = StrUtil.format("D:/Z0Temp/20250612/cert_code_{}_{}.sql", hosId, type);
        FileOutputStream fos = new FileOutputStream(fileName);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
        for (String str : logList) {
            bw.write(str);
            bw.newLine();
        }
        bw.close();
        fos.close();
    }
}
